from info import db
from info.models import News, User, Comment
from info.modules import news
from info.modules.news import news_blu
from flask import render_template, current_app, session, g, abort, jsonify, request

from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blu.route('/news_comment',methods=['POST'])
@user_login_data
def add_news_comment():
    '''
    添加新闻评论
    :return:
    '''
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')
    # 获取参数
    data_dict = request.json
    news_id = data_dict.get('news_id')
    comment_str = data_dict.get('comment')
    parent_id = data_dict.get('parent_id')

    # 判断如果没有获取到新闻id和评论内容，返回‘参数不足’
    if not all([news_id,comment_str]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不足')

    # 用获取到的新闻id从数据库中查寻新闻，如果没有返回'该新闻不存在’
    try:
        new = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')

    if not news:
        return jsonify(errno=RET.NODATA,errmsg='该新闻不存在')

    # 初始化模型，保存数据
    comment = Comment()
    # 用户评论id = 用户ID
    comment.user_id = user.id
    # 用户评论的这条新闻id= 这条新闻的id
    comment.news_id = news_id
    # 用户评论的内容和获取到的字符串一样
    comment.content = comment_str
    # 如果有parent_id
    if parent_id:
        comment.parent_id = parent_id

    # 保存到数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='保存评论数据失败')

    # 返回响应
    return jsonify(errno=RET.OK,errmsg='评论成功',data=comment.to_dict())





@news_blu.route('/news_collect',methods=['POST'])
@user_login_data
def collect_news():
    '''
    收藏新闻
    1. 接收参数
    2. 判断参数
    3. 查询新闻，并判断新闻是否存在
    :return:
    '''
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    # 1.接收参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 2.判断参数
    if not ([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    if action not in['collect','cancel_collect']:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 3.查询新闻，并判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据查询错误')

    if not news:
        return jsonify(errno=RET.NODATA,errmsg='未查询到新闻数据')

    # 4.收藏以及取消收藏
    if action == 'cancel_collect':
        # 取消收藏
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        # 收藏
        if news not in user.collection:
            # 添加到用户的新闻收藏列表
            user.collection_news.append(news)
    return jsonify(errno=RET.OK,errmsg='操作成功')


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    '''
    新闻详情
    :param news_id:
    :return:
    '''
    # 查询用户登录信息
    user = g.user

    # 右侧的新闻排行的逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    # 定义一个空的字典列表，将对象的字典添加到字典列表中
    news_dict_li = []
    # 遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list if news_list else []:
        news_dict_li.appen(news.to_basic_dict())

    # 查询新闻数据
    news = None

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        abort(404)

    # 更新新闻的点击次数
    news.clicks += 1

    is_collected = False

    if user:
        # 判断用户是否收藏当前新闻
        if news in user.collection_news:
            is_collected = True

    # 去查询评论数据
    comment = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_dict_li = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict_li.append(comment_dict)


    data = {
        'user': user.to_dict() if user else None,
        'news_dict_li': news_dict_li,
        'news':news.to_dict(),
        'is_collected':is_collected,
        'comments':comment_dict_li
    }
    return render_template('news/detail.html',data=data)
